/**
 * 请求封装
 */
const request = (url = '', type = 'GET', param = {}, Loading) => {
    var params = Object.assign({}, param);

    //是否启动加载
    if (Loading) {
        uni.showLoading({
            mask: true
        });
    }

    const header = {
        "Content-Type": "application/json; charset=utf-8"
    };

    return new Promise((resolve, reject) => {
        uni.request({
            method: type,
            url: url,
            data: params,
            header: header,
            dataType: 'json',
            withCredentials: true
        }).then((response) => {
            let [error, res] = response;
            //未登录拦截
            if (res.data.code == 101) {
                uni.removeStorageSync('token');
                window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx82dd5de1c159bb98&redirect_uri=http://www.szxlyc.com/open/wx/oauth?target=5&response_type=code&scope=snsapi_userinfo&code=CODE&state=STATE#wechat_redirect   '
                return false;
            }
            resolve(res.data);
            if (Loading) {
                uni.hideLoading();
            }
        }).catch(error => {
            uni.showToast({
                title: '网络出现问题',
                icon: 'error'
            });
            let [err, res] = error;
            reject(err);
        })
    });
}


/**
 * 平台判断
 */
const getPlatform = () => {
    let platform = uni.getSystemInfoSync().platform;
    if (platform == 'ios') {
        platform = 'ios';
    } else if (platform == 'android') {
        platform = 'android';
    }

    return platform;

}

/**
 * 来创建指定长度且所有元素都被初始化为 false 的数组
 */
const createArray = (length, value) => {
    return Array(length).fill(value);
}


/**
 * 截取字符串的前8个字符
 */
const getFirstEightChars = (str) => {
    return str.substring(0, 8);
}

/**
 * 设置cookit
 */
const setCookie = (name, value, time) => {
    let domain = '';
    const hostname = window.location.hostname;

    // 检查是否是IP地址
    const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname);

    if (!isIP) {
        // 如果不是IP地址，使用原来的域名逻辑
        domain = "; domain=" + hostname.split('.').slice(-2).join('.');
    }
    // 如果是IP地址，不设置domain

    const Days = time * 1;
    const exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${exp.toGMTString()}; path=/${domain ? `; domain=${domain}` : ''}`;
    return true;
}

/**
 *获取cookie
 */
const getCookie = (name) => {
    return document.cookie.split('; ').find(row => row.startsWith(name + '='))?.split('=')[1] || '';
}

/**
 *删除cookie
 */
const delCookie = (name) => {
    var domain = "; domain=" + window.location.hostname.split('.').slice(-2).join('.');
    var path = "; path=/";
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + domain + path;
        return true;
    } else {
        return false;
    }
}

/**
 *压缩图片
 */
const imageCompressor = (imagePath, quality = 0.9, maxWidth = 1000, maxHeight = 1000) => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = imagePath;
        img.onload = function() {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            let width = img.width;
            let height = img.height;

            // 按比例缩放
            if (width > height) {
                if (width > maxWidth) {
                    height = Math.round((height *= maxWidth / width));
                    width = maxWidth;
                }
            } else {
                if (height > maxHeight) {
                    width = Math.round((width *= maxHeight / height));
                    height = maxHeight;
                }
            }

            // 设置 canvas 宽高
            canvas.width = width;
            canvas.height = height;

            // 绘制图片
            ctx.drawImage(img, 0, 0, width, height);

            // 导出压缩后的图片
            const compressedImage = canvas.toDataURL('image/jpeg', quality);
            resolve(compressedImage);
        };

        img.onerror = function(err) {
            reject(err);
        };
    });
}

/**
 * 微信分享封装
 */
const initWechatShare = (shareConfig) => {
    return new Promise((resolve, reject) => {
        // 检查微信JSSDK是否加载
        if (typeof window.jWeixin === 'undefined') {
            console.error('微信JSSDK未加载');
            reject(new Error('微信JSSDK未加载'));
            return;
        }

        // 配置微信JSSDK
        window.jWeixin.config({
            debug: false,
            appId: shareConfig.appId,
            timestamp: shareConfig.timestamp,
            nonceStr: shareConfig.nonceStr,
            signature: shareConfig.signature,
            jsApiList: [
                'updateAppMessageShareData', // 分享给朋友
                'updateTimelineShareData' // 分享到朋友圈
            ]
        });

        // 配置成功回调
        window.jWeixin.ready(() => {
            console.log('微信JSSDK配置成功');
            
            // 设置分享数据
            var shareData = {
                title: shareConfig.title || '小朗优创', // 分享标题
                desc: shareConfig.desc || '小朗优创', // 分享描述
                link: shareConfig.link || window.location.href, // 分享链接
                imgUrl: shareConfig.imgUrl || '' // 分享图标
            };

            // 分享给朋友
            window.jWeixin.updateAppMessageShareData(shareData);

            // 分享到朋友圈
            window.jWeixin.updateTimelineShareData({
                title: shareData.title,
                link: shareData.link,
                imgUrl: shareData.imgUrl
            });

            resolve(shareData);
        });

        // 配置失败回调
        window.jWeixin.error((res) => {
            console.error('微信JSSDK配置失败:', res);
            reject(res);
        });
    });
}

module.exports = {
    request,
    getPlatform,
    createArray,
    getFirstEightChars,
    setCookie,
    getCookie,
    delCookie,
    imageCompressor,
    initWechatShare
}